package com.hup.joystick.view.quickMenu;

import com.hup.joystick.constant.FunctionConstant.QuickMenuFunctionType;
import com.hup.joystick.model.QuickMenuFunction;
import com.hup.joystick.service.JoyEventService;
import com.hup.joystick.service.QuickMenuFunctions;
import com.hup.joystick.view.quickMenu.QuickMenu.ItemHandler;
import com.hup.utils.commons.exception.AppCommonException;
import com.hup.utils.commons.start.DialogHelper;
import com.hup.utils.commons.start.LookThemeUtil;
import com.hup.utils.commons.start.SpringContext;
import com.hup.utils.swing.ComponentUtil;
import lombok.extern.log4j.Log4j2;
import sun.swing.SwingUtilities2;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 功能按钮item类
 * @author hugan
 * @date 2020/11/12
 */
@Log4j2
public class QMFunctionButton extends JButton implements ActionListener {
    private static final int UNIT = SwingUtilities2.getFontMetrics(null, LookThemeUtil.getDefaultScaledFont()).getHeight();
    private QuickMenuFunction function;

    public QMFunctionButton() {
        setBorder(new EmptyBorder(UNIT, UNIT, UNIT, UNIT));
        addActionListener(this);
    }

    private void initData(QuickMenuFunction function) {
        this.function = function;
        setText(function.getDesc());
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (function.type == QuickMenuFunctionType.CMD && QuickMenuFunctions.getCmdAction(function) == null) {
            DialogHelper.show(null, new AppCommonException("找不到内置功能:" + function.cmdDesc), ComponentUtil.getParentWindow(this));
            return;
        }
        ComponentUtil.getParentWindow(this).dispose();
        SpringContext.getBean(JoyEventService.class).exeFunction(function);
    }

    public static class QMFunctionButtonHandler implements ItemHandler<QMFunctionButton, QuickMenuFunction> {

        @Override
        public QMFunctionButton createItem() {
            return new QMFunctionButton();
        }

        @Override
        public void initData(QMFunctionButton item, QuickMenuFunction data) {
            item.initData(data);
        }
    }

}
